package swing.admin.dao;

import swing.admin.model.Major;
import swing.admin.model.Student;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class StudentDao extends BaseMapper<Student> {
    public StudentDao() {
        super(Student.class);
    }

    public List<Student> listAll() {
        List<Student> list = selectList("select * from student", null);
        return list;
    }

    public List<Student> list(Student queryParam) {

        StringBuilder sql = new StringBuilder("select * from student where 1=1");
        ArrayList<Object> param = new ArrayList<>();

        if (!Objects.isNull(queryParam.getId())) {
            sql.append(" and id = ?");
            param.add(queryParam.getId());
        }

        if (!Objects.isNull(queryParam.getMajorId())) {
            sql.append(" and major_id = ?");
            param.add(queryParam.getMajorId());
        }

        if (!Objects.isNull(queryParam.getName())) {
            sql.append(" and name = ?");
            param.add(queryParam.getName());
        }

        System.out.println(sql);
        List<Student> list = selectList(sql.toString(), param.toArray());
        return list;
    }

    public Student getById(Integer id) {
        return selectOne("select * from student where id = ?", id);
    }

    public void deleteById(Integer id) {
        boolean delete = delete("delete from student where id = ?", id);
    }

    public void updateById(Student model){
        StringBuilder sql = new StringBuilder("update student");
        ArrayList<Object> param = new ArrayList<>();

        if (!Objects.isNull(model.getMajorId())) {
            sql.append(" set major_id = ?");
            param.add(model.getMajorId());
        }

        if (!Objects.isNull(model.getName())) {
            sql.append(", name = ?");
            param.add(model.getName());
        }

        if (!Objects.isNull(model.getId())) {
            sql.append(" where id = ?");
            param.add(model.getId());
        }

        System.out.println(sql);

        int update = update(sql.toString(), param.toArray());
        System.out.println(update);
    }

    public void insert(Student model){
        ArrayList<Object> param = new ArrayList<>();
        param.add(model.getMajorId());
        param.add(model.getName());
        boolean insert = insert("insert into student(major_id, name) values(?, ?)", param.toArray());
    }
}
